<template>
  <div v-loading="loading" class="chart-container">
    <div class="time-filter">
      <el-date-picker
        v-model="timeRange"
        type="datetimerange"
        range-separator="-"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DDTHH:mm:ss"
      />
      <el-button type="primary" @click="fetchData">查询</el-button>
    </div>

    <v-chart :option="chartOptions" autoresize />
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts/core';
import { BarChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import VChart from 'vue-echarts';
import api from '@/api';
import dayjs from 'dayjs';

// 注册ECharts组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  BarChart,
  CanvasRenderer
]);

// 时间范围（默认近30天）
const timeRange = ref([
  dayjs().subtract(30, 'day').format('YYYY-MM-DDTHH:mm:ss'),
  dayjs().format('YYYY-MM-DDTHH:mm:ss')
]);

const loading = ref(true);
const chartData = ref([]);

// 生成24小时时间槽（2小时间隔）
const timeSlots = Array.from({ length: 12 }, (_, i) => {
  const start = i * 2;
  const end = (start + 2) % 24;
  return `${String(start).padStart(2, '0')}:00-${String(end).padStart(2, '0')}:00`;
});

// 获取统计数据
const fetchData = async () => {
  try {
    loading.value = true;

    // 构造请求参数
    const params = {
      start: timeRange.value[0],
      end: timeRange.value[1]
    };

    const res = await api.getHourlyStats(params);
    chartData.value = Array.isArray(res.data) ? res.data : [];
  } catch (err) {
    ElMessage.error(`数据加载失败: ${err.message}`);
    chartData.value = [];
  } finally {
    loading.value = false;
  }
};

// 初始化加载数据
fetchData();

// 图表配置
const chartOptions = computed(() => ({
  title: {
    text: timeRange.value?.length === 2
      ? `${dayjs(timeRange.value[0]).format('YYYY-MM-DD')} 至 ${dayjs(timeRange.value[1]).format('YYYY-MM-DD')} 入库统计`
      : '近期入库时段分布',
    left: 'center',
    textStyle: {
      fontSize: 16,
      fontWeight: 'normal'
    }
  },
  tooltip: {
    trigger: 'axis',
    formatter: '{b}<br/>{a}: {c} 辆'
  },
  xAxis: {
    type: 'category',
    data: timeSlots,
    axisLabel: {
      rotate: 45,
      margin: 15,
      fontSize: 12
    }
  },
  yAxis: {
    type: 'value',
    name: '车辆数',
    minInterval: 1,
    axisLabel: {
      fontSize: 12
    }
  },
  series: [{
    name: '入库数量',
    type: 'bar',
    barWidth: '60%',
    data: timeSlots.map(slot => {
      const match = chartData.value.find(item => item.time_slot === slot);
      return match?.count || 0;
    }),
    itemStyle: {
      color: '#409EFF',
      borderRadius: [3, 3, 0, 0]
    },
    label: {
      show: true,
      position: 'top',
      fontSize: 12
    }
  }],
  grid: {
    left: '3%',
    right: '3%',
    bottom: '18%',
    containLabel: true
  }
}));
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 450px;
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  position: relative;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.time-filter {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
  display: flex;
  gap: 10px;
  background: rgba(255,255,255,0.9);
  padding: 8px 15px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.el-date-editor {
  width: 360px;
}
</style>
